package xyz.poke.business.tool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import xyz.poke.business.tool.common.PageResult;
import xyz.poke.business.tool.constants.DbConstants;
import xyz.poke.business.tool.entity.Category;
import xyz.poke.business.tool.mapper.CategoryMapper;
import xyz.poke.business.tool.param.CategoryParam;
import xyz.poke.business.tool.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 类目表 服务实现类
 * </p>
 *
 * @author 迫壳
 * @since 2024-02-22
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public PageResult<Category> paging(CategoryParam param) {
        PageResult<Category> result = new PageResult<>();
        QueryWrapper<Category> qw = new QueryWrapper<Category>()
                .eq(DbConstants.IS_DEL, false);
        if (!StringUtils.isEmpty(param.getSearchField())) {
            qw.and(categoryQueryWrapper -> categoryQueryWrapper.like(DbConstants.CODE, param.getSearchField())
                    .or().like(DbConstants.NAME, param.getSearchField()));
        }
        Page<Category> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()), qw);
        BeanUtils.copyProperties(page, result);
        if (!result.isEmpty()) {
            // 查询父目录
            List<String> pCodes = result.getRecords().stream().map(Category::getPCode).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(pCodes)) {
                return result;
            }
            List<Category> categories = this.list(new QueryWrapper<Category>().eq(DbConstants.IS_DEL, false)
                    .in(DbConstants.CODE, pCodes));
            Map<String, Category> idOfCategoryMap = categories.stream()
                    .collect(Collectors.toMap(Category::getCode, Function.identity(), (t1, t2) -> t1));
            result.getRecords().forEach(o -> {
                if (Objects.nonNull(o.getPCode())) {
                    o.setPidName(idOfCategoryMap.get(o.getPCode()).getName());
                }
            });
        }
        return result;
    }
}
